package com.tangdi.production.mpaychl.service.impl.bailian.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import org.apache.commons.codec.binary.Base64;


public class CerUtil {
	
	public static String readPublicCer(String cerPth) throws Exception {
		
		CertificateFactory certificatefactory=CertificateFactory.getInstance("X.509");
//		FileInputStream bais=new FileInputStream(cerPth);
		
		InputStream bais = CerUtil.class.getResourceAsStream(cerPth);
		
		X509Certificate Cert = (X509Certificate)certificatefactory.generateCertificate(bais);
		PublicKey pk = Cert.getPublicKey();
        
        System.out.println("public key = " + Base64.encodeBase64String(pk.getEncoded()));
        return Base64.encodeBase64String(pk.getEncoded());
	}
	
	@SuppressWarnings("rawtypes")
	public static String readPrivateCer(String cerPth,String cerPassword) throws Exception {
		
		KeyStore ks = KeyStore.getInstance("PKCS12");  
//        FileInputStream fis = new FileInputStream(cerPth);
		
		InputStream fis = CerUtil.class.getResourceAsStream(cerPth);
        ks.load(fis, cerPassword.toCharArray()); 
        fis.close();
        Enumeration enumas = ks.aliases();  
        String keyAlias = null;  
        if (enumas.hasMoreElements())// we are readin just one certificate.  
        {  
            keyAlias = (String)enumas.nextElement();   
        }
        PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, cerPassword.toCharArray());
        
        System.out.println("private key = " + Base64.encodeBase64String(prikey.getEncoded()));
        return Base64.encodeBase64String(prikey.getEncoded());
	}
	
	
	
	
	public static void main(String[] args) throws Exception {
		System.out.println(readPublicCer("D:/cer/3001874258.cer"));
		
		System.out.println(readPrivateCer("D:/cer/3001874259.pfx","123456"));
	}
	
}
